package com.moyou.weichat.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.app.Notification.Builder;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.PathUtil;
import com.moyou.weichat.MainActivity;
import com.moyou.weichat.R;
import com.moyou.weichat.bean.ChatTypeBean;
import com.moyou.weichat.bean.MessageNotificationBean;
import com.moyou.weichat.chat.ChatActivity;
import com.moyou.weichat.chat.ChatManger;
import com.moyou.weichat.chat.ChatVerticalListAdater;
import com.moyou.weichat.dapter.BaseChatAdapter;
import com.moyou.weichat.dapter.ChatHolderView;
import com.moyou.weichat.listener.ChatSendTypeListener;
import com.moyou.weichat.view.ui.Constants;
import com.moyou.weichat.view.ui.EmoticonClickListener;
import com.moyou.weichat.view.ui.EmoticonEntity;
import com.moyou.weichat.view.ui.QqEmoticonsKeyBoard;
import com.moyou.weichat.view.ui.QqUtils;
import com.sj.emoji.EmojiBean;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Administrator on 2017/10/17 0017.
 * sj: 2017年10月17日16:09:37
 * name : ts
 * 用途： 聊天的工具类
 */

public class ChatUtils implements ChatHolderView.MenuCall {
    private String TAG = "ChatUtils";
    private static ChatUtils chatUtils;
    protected ConvenientBanner menuView;
    protected ChatHolderView chatHolderView;
    private Context mContext;
    private List<ChatTypeBean> chatTypeBeanList;
    private NotificationManager manager; //通知管理器
    private int Notification_ID; //通知的id
    private ChatSendTypeListener chatSendTypeListener;

    public void setChatSendTypeListener(ChatSendTypeListener chatSendTypeListener) {
        this.chatSendTypeListener = chatSendTypeListener;
    }

    private ChatUtils(Context mContext) {
        this.mContext = mContext;
        chatTypeBeanList = new ArrayList<>();
        manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public static ChatUtils getChatUtils(Context mContext) {
        return chatUtils == null ? chatUtils = new ChatUtils(mContext) : chatUtils;
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    public int sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, (con1, con2) -> {
            if (con1.first.equals(con2.first)) {
                return 0;
            } else if (con2.first.longValue() > con1.first.longValue()) {
                return 1;
            } else {
                return -1;
            }
        });
        return -1;
    }


    /**
     * Get digest according message type and content
     *
     * @param message
     * @param context
     * @return
     */
    public String getMessageDigest(EMMessage message, Context context) {
        String digest = "";
        switch (message.getType()) {
            case LOCATION:
                if (message.direct() == EMMessage.Direct.RECEIVE) {
                    digest = "[位置信息]";
                    digest = String.format(digest, message.getFrom());
                    return digest;
                } else {
                    digest = "[我发送的位置信息]";
                }
                break;
            case IMAGE:
                digest = "[图片]";
                break;
            case VOICE:
                digest = "[音频]";
                break;
            case VIDEO:
                digest = "[视频]";
                break;
            case TXT:
                EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                if (message.getBooleanAttribute(ConstantUtils.CHAT_VIDEO, false)) {
                    digest = "[电话拨打]" + txtBody.getMessage();
                } else if (message.getBooleanAttribute(ConstantUtils.CHAT_VIDEO, false)) {
                    digest = "[视频拨打]" + txtBody.getMessage();
                } else if (message.getBooleanAttribute(ConstantUtils.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
                    if (!TextUtils.isEmpty(txtBody.getMessage())) {
                        digest = txtBody.getMessage();
                    } else {
                        digest = "目前不知道什么东西";
                    }
                } else {
                    digest = txtBody.getMessage();
                }
                break;
            case FILE:
                digest = "未知错误";
                break;
            default:
                EMLog.e(TAG, "error, unknow type");
                return "";
        }
        return digest;
    }

    //区分所有的聊天类型
    public ChatTypeBean switchChatType(EMMessage messages) {
        //这里需要区分判断
        ChatTypeBean chatTypeBean = new ChatTypeBean();
        chatTypeBean.setMsgTime(messages.getMsgTime());
        switch (messages.getType()) {
            case LOCATION:
                chatTypeBean.setType(ConstantUtils.CHAT_TYPE_LEFT_TEXT);
                break;
            case IMAGE:
                EMImageMessageBody emImageMessageBody =  ((EMImageMessageBody) messages.getBody());
                if (messages.direct() == EMMessage.Direct.RECEIVE ){
                    chatTypeBean.setImageUrl(emImageMessageBody.thumbnailLocalPath());
                    chatTypeBean.setType(ConstantUtils.CHAT_TYPE_LEFT_IMAGE);
                    chatTypeBean.setNickName(messages.getUserName());
                }else{
                    chatTypeBean.setImageUrl(emImageMessageBody.getLocalUrl());
                    chatTypeBean.setType(ConstantUtils.CHAT_TYPE_RIGTH_IMAGE);
                }
                break;
            case VOICE:
                chatTypeBean.setType( ConstantUtils.CHAT_TYPE_LEFT_VOICE);
                break;
            case VIDEO:
                chatTypeBean.setType( ConstantUtils.CHAT_TYPE_LEFT_IMAGE);
                break;
            case TXT:
                String text = ((EMTextMessageBody) messages.getBody()).getMessage();
                if (messages.direct() == EMMessage.Direct.RECEIVE){
                    chatTypeBean.setType(ConstantUtils.CHAT_TYPE_LEFT_TEXT);
                    chatTypeBean.setNickName(messages.getUserName());
                }else{
                    chatTypeBean.setType(ConstantUtils.CHAT_TYPE_RIGHT_TEXT);
                }
                chatTypeBean.setContent(text);
                break ;
            case FILE:
//              chatTypeBean.setType(EMMessage.Type.FILE);
                break;
            default:
                EMLog.e(TAG, "error, unknow type");
        }
        return chatTypeBean;
    }


    public EmoticonClickListener getEtChat(QqEmoticonsKeyBoard qqEmoticonsKeyBoard) {

        EmoticonClickListener emoticonClickListener = (o, actionType, isDelBtn) -> {

            if (isDelBtn) {
                QqUtils.delClick(qqEmoticonsKeyBoard.getEtChat());
            } else {
                if (o == null) {
                    return;
                }
                if (actionType == Constants.EMOTICON_CLICK_BIGIMAGE || actionType == 3) {
                    if (o instanceof EmoticonEntity) {
                        //发送Gif
//                        gifImageApi.sendGif(((EmoticonEntity) o).getContent(), actionType);
                    }
                } else {

                    String content = null;
                    if (o instanceof EmojiBean) {
                        content = ((EmojiBean) o).emoji;

                    } else if (o instanceof EmoticonEntity) {
                        content = ((EmoticonEntity) o).getContent();
                    }
                    if (TextUtils.isEmpty(content)) {
                        return;
                    }
                    int index = qqEmoticonsKeyBoard.getEtChat().getSelectionStart();
                    Editable editable = qqEmoticonsKeyBoard.getEtChat().getText();
                    //这里是
                    editable.insert(index, content);
                }
            }
        };
        return emoticonClickListener;
    }

    //获取聊天记录
    public List<ChatTypeBean> getMessageAllList(String toChatUsername, Context mContext, int chatType) {
        EMConversation conversation = null;
        if (chatTypeBeanList == null)
            return null;
        chatTypeBeanList.clear();
        if (chatType == ConstantUtils.CHAT_TYPE_SING) {
            conversation = ChatManger.getChatManger().getChatMessageConversation(toChatUsername);
        } else if (chatType == ConstantUtils.CHAT_TYPE_GROUP) {
            conversation = ChatManger.getChatManger().getChatMessageConversation(toChatUsername);
        }
        conversation.markAllMessagesAsRead(); //标记已读消息被阅读
        //获取此会话的所有消息
        List<EMMessage> msgs = conversation.getAllMessages();
        getMessage(msgs ,conversation);
        return chatTypeBeanList;
    }

    public List<ChatTypeBean> getMessage( List<EMMessage> msgs ,EMConversation conversation){
        chatTypeBeanList.clear();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < 20) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            msgs.addAll(conversation.loadMoreMsgFromDB(msgId, 20 - msgCount));
        }
        //获取会话的type和内容
        for (EMMessage message : msgs) {
            chatTypeBeanList.add(ChatUtils.getChatUtils(mContext).switchChatType(message));
        }
        return chatTypeBeanList;
    }


    /**
     * 代码设置菜单栏
     *
     * @return
     */
    public View getMenuView(int chatType, Context context) {
        ArrayList<String> menuList = new ArrayList<>();
        if (chatType == 1) {
            menuList.add("menuOne");
        } else {
            menuList.add("menuOne");
            menuList.add("menuTwo");
        }
        menuView = new ConvenientBanner(context);
        chatHolderView = new ChatHolderView(chatType);
        chatHolderView.setMenuCall(this);
        menuView.setCanLoop(false);
        menuView.setPageIndicator(new int[]{R.drawable.find_dot_unseleted, R.drawable.chat_dot_seleted});
        menuView.setPages(new CBViewHolderCreator<ChatHolderView>() {
            @Override
            public ChatHolderView createHolder() {
                return chatHolderView;
            }
        }, menuList);
        return menuView;
    }

    //选择发送图片！
    @Override
    public void imageBtn() {
        chatSendTypeListener.sendImage();
    }

    //发送照相机图片！
    @Override
    public void cameraBtn() {
        chatSendTypeListener.sendCreamImage();
    }

    //录制视频
    @Override
    public void videoBtn() {
        chatSendTypeListener.sendVideo();
    }

    //发送定位
    @Override
    public void locationBtn() {
        chatSendTypeListener.sendLocation();
    }

    //发送 红包！
    @Override
    public void radBtn() {
        chatSendTypeListener.sendRed();
    }

    //推荐好友或者群！
    @Override
    public void friendBtn() {

    }

    //电话通话
    @Override
    public void voiceCommunicate() {

    }

    //视屏通话！
    @Override
    public void videoCommunicate() {

    }

    //收藏
    @Override
    public void collectBtn() {

    }

    //祝福语
    @Override
    public void cardBtn() {

    }

    //遍历获取到的消息
    public void getMessageData(List<EMMessage> messages, BaseChatAdapter baseChatAdapter, String pashChatId, List<ChatTypeBean> chatTypeBeenList) {
        for (EMMessage message : messages) {
            String username = null;
            // group message
            if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }
//            // if the message is for current conversation
            if (username.equals(pashChatId) || message.getTo().equals(pashChatId) || message.conversationId().equals(pashChatId)) {
                ChatTypeBean chatTypeBean = switchChatType(message);
                baseChatAdapter.refreshSelectLast(chatTypeBean, chatTypeBeenList);
//                EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);  //免打扰
                ChatManger.getChatManger().getChatMessageConversation(username).markMessageAsRead(message.getMsgId());  //设置一条消息的已读！
            } else {
//                EaseUI.getInstance().getNotifier().onNewMsg(message);  通知他
            }
        }
    }

    //删除某一条会话
    public void deleteMessage(String userName, int postion, ChatVerticalListAdater chatVerticalListAdater,
                              List<EMConversation> chatVeryocalList) {
        //删除和某个user会话，如果需要保留聊天记录，传false
        try {
            if (EMClient.getInstance().chatManager().deleteConversation(userName, false)) {
                chatVerticalListAdater.notifyItemRemoved(postion);
                chatVeryocalList.remove(postion); //删除元数据中的item
            } else {
                T.Tips("删除失败", mContext);
            }
        } catch (Exception e) {
            T.Tips("删除失败", mContext);
        }

    }

    //跳转聊天页面
    public void startChatActivity(String userNmae, EMConversation.EMConversationType type) {
        Intent intent = new Intent(mContext, ChatActivity.class);
        intent.putExtra("userNmae", userNmae);
        if (type == EMConversation.EMConversationType.Chat) {
            //单聊
            intent.putExtra("chatType", ConstantUtils.CHAT_TYPE_SING);
        } else if (type == EMConversation.EMConversationType.GroupChat) {
            //群聊
            intent.putExtra("chatType", ConstantUtils.CHAT_TYPE_GROUP);
        }
        mContext.startActivity(intent);
        MessageNotificationBean messageNotificationBean = new MessageNotificationBean();
        messageNotificationBean.setMessageType(ConstantUtils.CHAT_NOTIFICATION_REFSH);
        EventBus.getDefault().post(messageNotificationBean);
    }

    //提示通知
    public void showNotification(String userName, String content) {
        Notification.Builder builder = new Builder(mContext);
        builder.setSmallIcon(R.mipmap.ic_app_logo);//设置图标
        builder.setTicker(userName);//手机状态栏的提示
        builder.setContentTitle(userName);//设置标题
        builder.setContentText(content);//设置通知内容
        builder.setWhen(System.currentTimeMillis());//设置通知时间
        Intent intent = new Intent(mContext, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
        builder.setContentIntent(pendingIntent);//点击后的意图
        builder.setSound(Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.biubiu));//设置提示声音
        Notification notification;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            notification = builder.getNotification();//4.1以上，以下要用getNotification()
        } else {
            notification = builder.build();
        }
        manager.notify(Notification_ID, notification);
    }

    //发送文本消息
    public EMMessage createTextContent(String content, String toChatUsername, int chatType) {
        //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == ConstantUtils.CHAT_TYPE_GROUP)
            message.setChatType(EMMessage.ChatType.GroupChat);
        //发送消息
        EMClient.getInstance().chatManager().sendMessage(message);
        return message;
    }

    //发送图片消息
    public EMMessage createImageContent(String imagePath, String toChatUsername, int chatType) {
        //imagePath为图片本地路径，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == ConstantUtils.CHAT_TYPE_GROUP)
            message.setChatType(EMMessage.ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
        return message;
    }

    //发送语音消息
    public EMMessage createVioceContent(String filePath, int length, String toChatUsername, int chatType) {
        //filePath为语音文件路径，length为录音时间(秒)
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == ConstantUtils.CHAT_TYPE_GROUP)
            message.setChatType(EMMessage.ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
        return message;
    }

    //发送视频消息
    public EMMessage createVideoContent(String videoPath, int videoLength, String thumbPath, String toChatUsername, int chatType) {
        //videoPath为视频本地路径，thumbPath为视频预览图路径，videoLength为视频时间长度
        EMMessage message = EMMessage.createVideoSendMessage(videoPath, thumbPath, videoLength, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == ConstantUtils.CHAT_TYPE_GROUP)
            message.setChatType(EMMessage.ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
        return message;
    }

    //发送地理位置消息
    public EMMessage createLocationContent(double latitude, double longitude, String locationAddress, String toChatUsername, int chatType) {
        //latitude为纬度，longitude为经度，locationAddress为具体位置内容
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        //如果是群聊，设置chattype，默认是单聊
        if (chatType == ConstantUtils.CHAT_TYPE_GROUP)
            message.setChatType(EMMessage.ChatType.GroupChat);
        EMClient.getInstance().chatManager().sendMessage(message);
        return message;
    }

    /**
     * change the chat type to EMConversationType
     *
     * @param chatType
     * @return
     */
    public static EMConversation.EMConversationType getConversationType(int chatType) {
        if (chatType == ConstantUtils.CHAT_TYPE_SING    ) {
            return EMConversation.EMConversationType.Chat;
        } else if (chatType == ConstantUtils.CHAT_TYPE_GROUP) {
            return EMConversation.EMConversationType.GroupChat;
        } else {
            return EMConversation.EMConversationType.ChatRoom;
        }
    }
}
